//
// Created by jerry on 2021/4/5.
//
#include <stdio.h>
#include <string.h>

#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "tcp_socket.h"

#define DEBUG 1
#define LOGD(fmt, ...) {if (DEBUG == 1 ) printf("[D][%s:%d] "fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}

/* 关闭socket套接字 */
void close_tcp_socket(int fd)
{
    close(fd);
}

/* 建立tcp链接 */
int open_tcp_socket_connect()
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);

    if (fd <= 0)
    {
        LOGD("open socket failed!");
        return -1;
    }

    const char *server_ip      = TCP_SERVER_IP;
    unsigned short server_port = TCP_SERVER_PORT;

    struct sockaddr_in serverAddr;
    bzero(&serverAddr, sizeof(serverAddr));

    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port   = htons(server_port);
    inet_pton(AF_INET, server_ip, &serverAddr.sin_addr);

    if (0 != connect(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)))
    {
        LOGD("tcp connect failed!");
        close_tcp_socket(fd);
        return -1;
    }

    return fd;
}

/* 发送消息并关闭tcp链接 */
int send_message(struct TCP_MSG *tcpMsg)
{
    if (!tcpMsg || tcpMsg->msgLength == 0 || !tcpMsg->msg)
    {
        LOGD("TCP_MSG or msgLength or msg is NULL, return.");
        return -1;
    }

    int fd = open_tcp_socket_connect();
    if (0 > fd)
    {
        return  -1;
    }

    int len = send(fd, tcpMsg->msg, tcpMsg->msgLength, 0);
    if (0 >= len)
    {
        LOGD("send tcp message failed!");
    }

    close_tcp_socket(fd);

    return 0;
}
